package com.its.us.netty.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 群聊天
 * @Author: master
 * @Date: 2020/11/1 19:45
 * @Version: 1.0
 */
public class WebManySocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 全局单例实例化唯一
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //System.err.println("服务器端收到消息：" + msg.text());
        // 回复消息
        //ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间：" + LocalDateTime.now() + " " + msg.text()));
        Channel inComing = ctx.channel();

        channelGroup.forEach(ch -> {
            if (ch != inComing) {
                ch.writeAndFlush(new TextWebSocketFrame("客户[" + inComing.remoteAddress() + "]：" + msg.text() + " 时间：" + LocalTime.now()));
            } else {
                ch.writeAndFlush(new TextWebSocketFrame("自己[" + inComing.remoteAddress() + "]：" + msg.text() + " 时间：" + LocalTime.now()));
            }
        });
    }

    /**
     * 当web客户端连接后就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // id 表示唯一的值，LongText 是唯一的
        //System.err.println("handlerAdded 被调用了" + ctx.channel().id().asLongText());
        // 不是唯一的，有可能重复
        //System.err.println("handlerAdded 被调用了" + ctx.channel().id().asShortText());
        ctx.channel().writeAndFlush("[server-]" + ctx.channel().remoteAddress() + "channel_id" + ctx.channel().id() + "加入了 \n");
        // 添加到通道组
        channelGroup.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.err.println("handlerRemoved 被调用了" + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("异常发生：" + cause.getMessage());
        ctx.close();
    }
}
